﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command;
using B.S.BasicData.Api.Read.Application.Command.RBAC;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.RBAC
{
    public class UpdateUserHandler : IRequestHandler<UpdateUserCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IMapper mapper;

        public UpdateUserHandler(IBaseRepository<RoleModel> roleRepo,IMapper mapper)
        {
            this.roleRepo = roleRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
           var res=new ApiResult<int>();
            var role = roleRepo.GetAll().Where(x => x.RoleName == request.RoleName && x.RoleId != request.RoleId).FirstOrDefault();
            if (role != null)
            {
                res.Message = "角色名称已存在";
                res.Code = ApiEnum.Error;
                return Task.FromResult(res);
            }
            var entity = mapper.Map(request, role);
            var r = roleRepo.Update(entity).Result;
            if (r > 0)
            {
                res.Message = "修改成功";
                res.Code = ApiEnum.Ok;
                res.Data = r;
            }
            else
            {
                res.Message = "修改失败";
                res.Code = ApiEnum.Error;
                res.Data = r;
            }
            return Task.FromResult(res);
        }
    }
}
